using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Core.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tool.Web.HttpHelper;
using Tool.Windows.Win32;
using WebSocket4Net;

namespace Core.WebSocketClient
{
	public static class Client
	{
		private static WebSocket Socket;

		private static bool IsRun;

		public static void Open()
		{
			IsRun = true;
			if (Socket == null)
			{
				Socket = new WebSocket(Global.ServerAddressWebSocket);
				Socket.Opened += Opened;
				Socket.Error += Error;
				Socket.Closed += Closed;
				Socket.MessageReceived += MessageReceived;
				new Thread((ThreadStart)delegate
				{
					string message = JsonConvert.SerializeObject(new CheckHeart());
					while (true)
					{
						Thread.Sleep(180000);
						if (IsRun)
						{
							Socket.Send(message);
						}
					}
				}).Start();
			}
			Socket.Open();
		}

		public static void Close()
		{
			IsRun = false;
			Socket.Close();
		}

		private static void Opened(object sender, EventArgs e)
		{
			Global.CQ.Log("服务器连接成功");
			Socket.Send(JsonConvert.SerializeObject(new Bot
			{
				Action = "SendBotInfo",
				BotNum = Global.CQ.GetLoginQQ(),
				MasterNum = Global.Master,
				Version = Global.Version
			}));
		}

		private static void Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
		{
			Global.CQ.Log("连接发生了错误,错误信息：" + e.Exception.Message);
		}

		private static void Closed(object sender, EventArgs e)
		{
			if (IsRun)
			{
				Global.CQ.Log("未能连接服务器,稍后将重新连接");
				Thread.Sleep(10000);
				try
				{
					Socket.Open();
				}
				catch (Exception)
				{
				}
			}
		}

		private static void MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			JObject jObject = JObject.Parse(e.Message);
			string a = jObject["Action"].ToString();
			if (a == "AddLog")
			{
				Global.CQ.Log(jObject["Message"].ToString());
			}
			else if (a == "SendMasterMessage")
			{
				Global.CQ.SendPrivateMessage(Global.Master, jObject["Message"].ToString());
			}
			else if (a == "CanRun")
			{
				Global.CanUse = jObject["Value"].ToObject<bool>();
				Global.Csh?.Invoke(Global.CanUse, Global.Authorization, false);
			}
			else if (a == "UpdataMessage")
			{
				if (jObject["Force"].ToObject<bool>())
				{
					File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "app\\com.acgdmzy.acg.cpk", HttpNet.Get(Global.ServerAddressFile + "com.acgdmzy.acg.cpk"));
					FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "app\\com.acgdmzy.acg.cpk");
					Global.CQ.SendPrivateMessage(Global.Master, string.Format("少看点二次元吧推送了更新\r\n版号：{0}\r\n更新内容：{1}\r\n本次为强制更新,插件已经下载完毕({2}kb),酷Q将会重载插件以应用更新", jObject["version"], jObject["Message"], (fileInfo.Length / 1024.0).ToString("0.00")));
					Win32Help.IniWriteValue(Global.AppDir + "通用设置.ini", "设置", "重启", "1");
					Process.Start(Global.AppDir + "重载.exe");
				}
				else
				{
					jObject["type"].ToObject<int>();
					Global.CQ.SendPrivateMessage(Global.Master, string.Format("少看点二次元吧推送了更新\r\n版号：{0}\r\n更新内容：{1}\r\n本次为非强制更新,你可以向我发送【更新插件】来更新", jObject["version"], jObject["Message"]));
				}
			}
		}
	}
}
